<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/7/22
 * Time: 15:54
 */

namespace app\index\controller;


use app\common\model\UrlsModel;
use think\facade\Request;
use think\facade\Validate;

class Url extends Base
{
    public function index(){
        $urlModel = new UrlsModel();
        return view();
    }

    /**
     * 添加短网址
     */
    public function add(){
        $param = Request::param();
        $urlsModel = new UrlsModel();
        $rule = [
            'short_code'  => 'alphaNum|max:9',
            'origin_url'   => 'max:600|require',
        ];

        $msg = [
            'short_code.alphaNum' => '短码只能为数字与字母的组合',
            'short_code.max'     => '短码最多不能超过9个字符',
            'origin_url.max'  => '网址长度不能超过600字符',
            'origin_url.require'  => '网址必须传',
        ];


        $validate   = Validate::make($rule,$msg);
        $result = $validate->check($param);
        if(!$result) {
           return json(array('error'=>1,'msg'=>$validate->getError()));
        }
        $ret = $urlsModel->createUrl($param['origin_url'],isset($param['short_code'])?$param['short_code']:'');
        if($ret['error']==0){
            return json(array('error'=>0,'msg'=>'保存成功'));
        }
        return json(array('error'=>1,'msg'=>'保存失败'));
    }
}